package com.nutstudy.ioc.test;

import com.nutstudy.ioc.spring.BeanPostProcessor;
import com.nutstudy.ioc.spring.NutComponent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: HyoJoo-W
 * @date: 2021-07-29 13:58
 * @description: 方法的返回值即为代理对象
 */

@NutComponent
public class NutBeanPostProcessor implements BeanPostProcessor
{
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
    {
        if (beanName.equals("userService"))
        {
//            System.out.println("[后置处理器]初始化前...");
//            System.out.println(bean);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
    {
        if (beanName.equals("userService"))
        {
//            System.out.println("[后置处理器]初始化后...");
            Object proxyInstance = Proxy.newProxyInstance
                    (NutBeanPostProcessor.class.getClassLoader(),
                     bean.getClass().getInterfaces(),
                     new InvocationHandler()
                     {
                         @Override
                         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
                         {
                             System.out.println("代理逻辑...");
                             return method.invoke(bean, args);
                         }
                     });
            //返回代理对象,并放入容器中
            return proxyInstance;
        }

        return bean;
    }
}
